package controller;

import com.google.gson.Gson;
import entry.Books;

import service.BookService;
import service.BookServiceImpl;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;


@WebServlet("/book/*")
public class BookServlet extends HttpServlet {

    private BookService bookService=new BookServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        String  url=request.getRequestURI();
        String methodName=url.substring(url.lastIndexOf("/")+1);
        System.out.println(methodName);
        Class cla= BookServlet.class;
        try {
            Method method = cla.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            System.out.println(method);
            method.invoke(cla.newInstance(),request,response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    //查询全部数据

    //按条件查询数据
    public void queryByBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String query=request.getParameter("query");
        String str=request.getParameter("str");
        Books book=new Books();
        if("1".equals(query)){
            book.setBookName(str);
        }else if ("2".equals(query)){
            book.setBookAuthor(str);
        }else if ("3".equals(query)){
            book.setBookPublish(str);
        }
        ArrayList<Books> books = bookService.selectMatch(book);
        Gson gson=new Gson();
        response.getWriter().println(gson.toJson(books));
    }
}
